package com.ego.auth.controller;

import com.ego.auth.entity.UserInfo;
import com.ego.auth.prop.JwtProperties;
import com.ego.auth.service.AuthService;
import com.ego.auth.utils.JwtUtils;
import com.ego.common.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Resource
    private JwtProperties jwtProperties;


    @PostMapping("/accredit")
    public ResponseEntity<Void> accredit(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //看一下有没得相关username和password的
        UserInfo userInfo = authService.getUserInfo(username, password);
        //判断如果没得的话，直接return
        if (userInfo == null) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        //如果有的话,这个返回一个jwt给客户端,写在cookie中
        String token;
        token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire()*60);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过请求头携带的cookie,获取到value,然后对他进行解析,拿到userInfo
     *
     * @param token
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("EGO_TOKEN") String token,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {
        UserInfo userInfo;
        try {
            userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            //刷新token
            token = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            //重新存放到cookie中
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getExpire()*60);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }


}
